﻿using FastIOC.Application;
using FastIOC.Attribute;
using FastIOC.Enum;
using FastUtil.Convert;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace FastCloud.Base.Config
{
    public class InjectContext
    {
        private static ContainerBuilder Container;
        public static void Init()
        {
            InjectFrameWork();
            InjectProject();
            Container.EnableIntecept(typeof(BaseController));
            Container.Build(CotainerEnum.BuidlModel.OverWrite);
        }

        public static void InjectFrameWork()
        {
            Container = ContainerBuilder.GetInstance();
            //获框架取所有程序集
            List<Assembly> assemblies = CloudUtil.GetFrameworkAssemblys();
            //注入框架所有Component组件
            Container.RegisterAssemblyTypes(assemblies.ToArray(), typeof(Component), true);
            //注入框架所有Service
            Container.RegisterAssemblyTypes(assemblies.ToArray(), typeof(Service), true);
        }

        public static void InjectProject()
        {
            //获取所有项目程序集
            List<Assembly> projectassemblies = PluginManage.GetDillList();
            //注入项目所有Component组件
            Container.RegisterAssemblyTypes(projectassemblies.ToArray(), typeof(Component), true);
            //注入项目所有Service
            Container.RegisterAssemblyTypes(projectassemblies.ToArray(), typeof(Service), true);
        }

        public static List<Type> GetClassTypeByAttribute(Type AttributeType)
        {
            List<Type> TypeList = new List<Type>();
            List<Assembly> assemblies = CloudUtil.GetFrameworkAssemblys();
            List<Assembly> projectassemblies = PluginManage.GetDillList();
            foreach (Assembly assItem in assemblies)
            {
                TypeList.AddRange(StructConvert.ConvertArrayToList(assItem.GetTypes()).FindAll(a => a.GetCustomAttribute(AttributeType, true) != null));
            }
            foreach (Assembly assItem in projectassemblies)
            {
                TypeList.AddRange(StructConvert.ConvertArrayToList(assItem.GetTypes()).FindAll(a => a.GetCustomAttribute(AttributeType, true) != null));
            }
            return TypeList;
        }

        public static object Resolve(Type Type, CotainerEnum.TypeEqual TypeEqual = CotainerEnum.TypeEqual.Ref)
        {
            return Container.Resolve(Type, TypeEqual);
        }

        public static T ResolveNamed<T>(string Name)
        {
            return Container.ResolveNamed<T>(Name);
        }

        public static List<Type> GetRegistType(Type @Type)
        {
            return Container.GetRegistType(@Type);
        }
    }
}
